<template>
  <div id="main" class="my-scroller" :style="{width:winStyle.width,height:winStyle.height}" v-show="isInit!==0">
    <template v-if="isInit>0">
      <router-view/>
      <my-nav :max-width="navMaxWidth" :top="navTop"/>
      <send-sms-dialog/>
      <product-choose-model-dialog/>
      <cart-submit-dialog/>
      <shop-send-time-dialog/>
      <choose-date-time-dialog/>
      <choose-date-dialog/>
      <order-express-more-dialog/>
      <choose-log-form-dialog/>
      <choose-sex-dialog/>
      <choose-product-classify-dialog/>
      <choose-coupon-dialog/>
      <choose-send-type-dialog/>
      <group-order-join-dialog/>
      <my-socket/>
      <choose-order-pay-type-dialog/>
      <change-city-dialog/>
      <commission-detail-dialog/>
      <member-recharge-dialog/>
      <jpush ref="jpush"/>
      <demo-dialog/>
      <message-dialog/>
      <shop-skill-product-dialog/>
      <show-notice-dialog/>
      <choose-invoice-info-dialog/>
      <show-system-apply-log-dialog/>
      <level-info-dialog/>
      <buy-vip-dialog/>
      <choose-order-search-dialog/>
      <app-version/>
      <add-cart-product-model-dialog/>
      <cart-util/>
      <my-slider-captcha/>
    </template>

    <server-error v-if="isInit===-1"/>
    <!--    <div style="position: fixed; width: 100px; height: 100px; background: red; top: 50px; right: 50px"-->
    <!--         @click="clearChoose">-->
    <!--    </div>-->
  </div>
</template>

<script>
import MyNav from './components/common/MyNav'
import SendSmsDialog from './components/common/SendSmsDialog'
import ProductChooseModelDialog from './components/common/ProductChooseModelDialog'
import CartSubmitDialog from './components/common/CartSubmitDialog'
import ShopSendTimeDialog from './components/common/ShopSendTimeDialog'
import ChooseDateTimeDialog from './components/common/ChooseDateTimeDialog'
import OrderExpressMoreDialog from './components/common/OrderExpressMoreDialog'
import ChooseLogFormDialog from './components/common/ChooseLogFormDialog'
import ChooseSexDialog from './components/common/ChooseSexDialog'
import ChooseDateDialog from './components/common/ChooseDateDialog'
import MySocket from './components/common/MySocket'
import ChooseProductClassifyDialog from './components/common/ChooseProductClassifyDialog'
import ChooseCouponDialog from './components/common/ChooseCouponDialog'
import ChooseSendTypeDialog from './components/common/ChooseSendTypeDialog'
import GroupOrderJoinDialog from './components/common/GroupOrderJoinDialog'
import ChooseOrderPayTypeDialog from './components/common/ChooseOrderPayTypeDialog'
import ChangeCityDialog from './components/common/ChangeCityDialog'
import CommissionDetailDialog from './components/common/CommissionDetailDialog'
import Vue from 'vue'
import CurrUser from './components/global/CurrUser'
import MemberRechargeDialog from './components/common/MemberRechargeDialog'
import Jpush from './components/common/Jpush'
import DemoDialog from './components/common/DemoDialog'
import MessageDialog from './components/common/MessageDialog'
import ShopSkillProductDialog from './components/common/ShopSkillProductDialog'
import ShowNoticeDialog from './components/common/ShowNoticeDialog'
import ChooseInvoiceInfoDialog from './components/common/ChooseInvoiceInfoDialog'
import ShowSystemApplyLogDialog from './components/common/ShowSystemApplyLogDialog'
import LevelInfoDialog from './components/common/LevelInfoDialog'
import BuyVipDialog from './components/common/BuyVipDialog'
import ChooseOrderSearchDialog from './components/common/ChooseOrderSearchDialog'
import AppVersion from './components/tools/AppVersion'
import MapTools from './components/tools/MapTools'
import AddCartProductModelDialog from './components/common/AddCartProductModelDialog'
import CartUtil from './components/common/CartUtil'
import SignUtil from './components/tools/SignUtil'
import ServerError from './components/common/ServerError'
import MySliderCaptcha from './components/common/MySliderCaptcha'

export default {
  name: 'App',
  components: {
    MySliderCaptcha,
    ServerError,
    CartUtil,
    AddCartProductModelDialog,
    AppVersion,
    ChooseOrderSearchDialog,
    BuyVipDialog,
    LevelInfoDialog,
    ShowSystemApplyLogDialog,
    ChooseInvoiceInfoDialog,
    ShowNoticeDialog,
    ShopSkillProductDialog,
    MessageDialog,
    DemoDialog,
    Jpush,
    MemberRechargeDialog,
    CommissionDetailDialog,
    ChangeCityDialog,
    ChooseOrderPayTypeDialog,
    GroupOrderJoinDialog,
    ChooseSendTypeDialog,
    ChooseCouponDialog,
    ChooseProductClassifyDialog,
    MySocket,
    ChooseDateDialog,
    ChooseSexDialog,
    ChooseLogFormDialog,
    OrderExpressMoreDialog,
    ChooseDateTimeDialog,
    ShopSendTimeDialog,
    CartSubmitDialog,
    ProductChooseModelDialog,
    SendSmsDialog,
    MyNav
  },
  mounted () {
    this.preInit(()=>{
      this.init()
      setTimeout(()=>{
        this.removeLoading()
      },2000)
    })
  },
  data: function () {
    return {
      isInit:0,
      winStyle: {
        width: 'auto',
        height: 'auto',
      },
      navMaxWidth: '',
      navTop: '',
      paddingTop: 0
    }
  },
  methods: {
    removeLoading: function () {
      document.getElementById('main-page-loading').remove()
      this.$forceUpdate()
      // console.log('this.removeLoading()')
    },
    preInit:function (callback) {
      this.$http.post(this.ApiDoNameCommon + 'Public/wo1mzi2dc4i9mnfbx5po', {}, {}).then((response) => {
        if (response.ok) {
          this.isInit = 1
          SignUtil.setConfig(response.body)
          typeof callback === 'function' ? callback() : ''
        } else {
          this.removeLoading()
          this.isInit = -1
        }
        this.$forceUpdate()
      }, () => {
        this.removeLoading()
        this.isInit = -1
        this.$forceUpdate()
      })
    },
    init:function () {
      this.addVisitLog(this.$route.name)
      let $this = this
      $this.paddingTop = $this.getSafeArea().top

      // if (localStorage.getItem('AppAgreement') !== '1') {
      //   $this.$refs['my-app-agreement-dialog'].open()
      //   return
      // }
      // 375  667
      var winSize = this.getWinSize()
      if (this.$route.query.onlyH5){
        this.winStyle.width = winSize.width+'px'
        this.winStyle.height = winSize.height+'px'
        this.navMaxWidth = winSize.width+'px'
        this.navTop = (winSize.height-50)+'px'
      }else if (winSize.width > 1024) {
        this.winStyle.width = '375px'
        this.winStyle.height = '667px'
        this.navMaxWidth = '375px'
        this.navTop = '627px'
      }


      // 登录用户检查线上登录状态
      if ($this.CurrUser.IsLogin()) {
        $this.getUserInfo()
        $this.bus.$emit('UserLoginCallBus')
      }


      // 重新自动定位
      $this.bus.$on('StartLocationCallBus', function (token) {
        $this.startLocation()
      })

      // 登录成功,重新获取是否绑定店铺状态
      $this.bus.$on('UserLoginCallBus', function (token) {
        setTimeout(function () {
          $this.getUserInfo()
        }, 1000)

        if (localStorage.getItem('TaPushToken')){
          setTimeout(function () {
            $this.MyRequest($this.ApiDoNameMember + 'Member/updateTaPushToken', {
              token: localStorage.getItem('TaPushToken')
            }, function (data) {
              // $this.$refs['jpush'].setTag()
              $this.$forceUpdate()
            }, function (msg) {
              $this.$message.error(msg)
              // $this.form.password = ''
            })
          }, 500)
        }
      })

      // 登录成功,重新获取是否绑定店铺状态
      $this.bus.$on('CartAddCallBus', function (type, shopProductStockId, nums, model, callback) {
        $this.setItemRequest(type, shopProductStockId, nums, model, callback)
      })

      // $this.setLocationCity('108.94,34.28')
      setTimeout(function () {
        if (typeof plus !== 'undefined') {
          // plus.nativeUI.alert('组件以获取')
          $this.setCurrCity()
          // plus.navigator.hideSystemNavigation()
        }
      }, 1500)

      setTimeout(function () {
        $this.getLastNotice()
      }, 350)
    },
    setDefaultCity: function () {
      // this.$message.warning('默认城市【榆林市】')
      this.CurrUser.setLocation('111.016431,39.015658')
      this.CurrUser.setCity('榆林市')
    },
    setCurrCity: function () {
      let $this = this

      // $this.startLocation()

      // $this.getAndUsePermission('location',$this.startLocation)

    },
    // 开始定位操作
    startLocation: function () {


      let $this = this

      // 暂时停止
      // $this.setDefaultCity()
      // return;
      // 不进行实时定位
      // console.log('AutoLocation',localStorage.getItem('AutoLocation'))

      if (localStorage.getItem('AutoLocation')==="0"){
        return;
      }else{
        if (localStorage.getItem('AutoLocation')==="2"){
          $this.getPositionAndCallBack(function (wgs84togcj02Location) {
            $this.setLocationCity(wgs84togcj02Location)
          })
        }else{
          $this.$confirm('您是否同意，根据当前位置自动定位城市?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // alert('确取获取地址')
            localStorage.setItem('AutoLocation',"2")
            $this.getPositionAndCallBack(function (wgs84togcj02Location) {
              $this.setLocationCity(wgs84togcj02Location)
            },true)
          }).catch(() => {
            localStorage.setItem('AutoLocation',"0")
            $this.setDefaultCity()
          })
        }


      }

      // alert(typeof plus)
      if (typeof plus !== 'undefined') {
        /* plus.nativeUI.confirm('您是否要根据当前定位，设置城市?', function (e) {
          if (e.index === 0) {
            plus.geolocation.getCurrentPosition(function (p) {
              let tmpLocation = p.coords.longitude + ',' + p.coords.latitude
              console.log('获取到当前定位是: ', tmpLocation)
              $this.setLocationCity(tmpLocation)
            }, function (e) {
              plus.nativeUI.toast('获取位置失败，请检查权限是否开启')
              // plus('Geolocation error: ' + e.message);
            })
          }else{
            // 不进行实时定位
            localStorage.setItem('NoAutoLocation',"1")
          }
        })
 */



          // 开始获取当前位置



      }else{
        $this.setDefaultCity()
      }
    },
    // 根据设置定位城市
    setLocationCity: function (tmpLocation) {
      let $this = this
      var searchCity = ''
      // 根据经纬度,查询城市
      $this.getCityByLocation(tmpLocation, function (response) {
        searchCity = ''
        // 检索覆盖城市
        $this.dict.CoverCity.forEach(function (provinceItem, index) {
          provinceItem.list.forEach(function (city, _index) {
            if (city.name === response.addressComponent.city) {
              searchCity = city.name
            }
          })
        })

        if (!searchCity) {
          if (localStorage.getItem('currCity') != '榆林市') {
            console.log('当前城市未覆盖,已经切换至【榆林市】')
            $this.successTip('当前城市未覆盖,已经切换至【榆林市】', 'warning', 5000)
            $this.setDefaultCity()
          } else {
            console.log('无需切换城市')
          }
          return
        } else {
          if (response.addressComponent.city !== $this.CurrUser.City) {
            $this.CurrUser.setCity(searchCity)
            $this.CurrUser.setLocation(tmpLocation)
            $this.$message.success('定位获取成功,已切换至【' + searchCity + '】,首页即将重载')
            setTimeout(function () {
              location.reload()
            }, 2000)
          } else {
            // $this.$message.success('定位获取成功,定位至【' + searchCity + '】')
          }
        }

      })
      $this.CurrUser.setLocation(tmpLocation)
    },
    getLastNotice: function () {
      let $this = this
      var id = 0
      if (!localStorage.getItem('ShowNotice_0')) {
        id = 0
      } else {
        id = localStorage.getItem('ShowNotice_0')
      }
      $this.MyRequest($this.ApiDoNameMember + 'Public/getLastNotice', {id: id ? id : 0}, function (data) {
        if (!data || !data.id) {
          return
        }
        $this.bus.$emit('ShowNoticeDialogCallBus', data, 0)
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
        // $this.form.password = ''
      })
    },
    // 如果有登录状态,则获取会员信息
    getUserInfo: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'Member/info', {}, function (data) {
        if (data.bindingShopNums === 0) {
          localStorage.setItem('isShifu', '0')
        } else {
          localStorage.setItem('isShifu', '1')
        }
        localStorage.setItem('currMemberId', data.id)
        // $this.$refs['jpush'].setTag()
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
        // $this.form.password = ''
      })

    },
    // 增加商品至购物车
    setItemRequest: function (type, shopProductStockId, nums, model, callback) {
      model = model ? model : ''
      let $this = this
      var api = 'Public/setCartItem'
      if ($this.CurrUser.IsLogin()) {
        api = 'Member/setCartItem'
      }
      $this.MyRequest($this.ApiDoNameMember + api, {type, shopProductStockId, nums, model}, function () {
        if (typeof callback === 'function') {
          callback({code: 0})
        }
      }, function (res) {
        if (typeof callback === 'function') {
          callback(res)
        }
      })
    }
  }
}
</script>

<style>
@import "assets/css/common.css";
@import "https://at.alicdn.com/t/c/font_3589419_uyr1yl6uuy.css?spm=a313x.7781069.1998910419.80&file=font_3589419_uyr1yl6uuy.css";
</style>
